#include <stdlib.h>
#include <limits.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <sys/param.h>
#include <fcntl.h>
#include <unistd.h>
#include <dirent.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>

#include "utils.h"
#include "xmalloc.h"
#include "string.h"


bool
isdir(const char * path) {
  struct stat buf;

  if (path == NULL) return (false);
  if (stat(path, &buf) == 0) {
    if (S_ISDIR(buf.st_mode)) return (true);
      else return (false);
  } else {
    E("Can't stat %s: %s(%d)", path, strerror(errno), errno);
    return (false);
  }
}

bool
rpath(char *path, char rpath[MAXPATHLEN+1])
{
  memset(rpath, 0, MAXPATHLEN+1);
  if ( realpath(path, rpath) == NULL ) return (false);
  return (true);
}

string_t *
check_rpath(const char *doc_dir, const char *uri)
{
  char *rlpth = ncmalloc(MAXPATHLEN+1, sizeof(char));
  string_t *path = create_string(doc_dir);

  add_string(path, uri);
  realpath(get_string(path), rlpth);
  if (indexOf(rlpth, doc_dir) == 0) {
    set_string(path, rlpth);
  } else set_string(path, "");
  ncfree(rlpth, (MAXPATHLEN+1)*sizeof(char));
  return (path);
}

long
indexOf(const char *str, const char *substr)
{
  char *dest = strstr(str, substr);
  long pos;

  if (dest) {
    pos = dest - str;
  } else return (-1);
  if (pos >= 0) return (pos);
    else return (-1);
}


char *
gen_random_str(char **dst, const size_t len)
{
  struct timeval t1;
  char s[len+1];
  static const char alphanum[] =
    "0123456789"
    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
    "abcdefghijklmnopqrstuvwxyz";

  gettimeofday(&t1, NULL);
  srand(t1.tv_usec * t1.tv_sec);
  memset(s, 0, len+1);
  for (size_t i = 0; i < len; ++i) {
    s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
  }

  if (dst) {
    if (*dst) {
      strncpy(*dst, s, len);
    }
  }
  (*dst)[len] = '\0';
  return (*dst);
}

